package fragment;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import com.example.mywood.ApplicationActivity;
import com.example.mywood.ImageActivity;
import com.example.mywood.LoginActivity;
import com.example.mywood.R;
import com.example.mywood.SearchActivity;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import adapter.ApplicationRecyclerViewAdapter;
import adapter.ImageAdapter;
import bean.ApplicationDataBean;
import bean.ContentDataBean;
import bean.ShaixuanBean;
import myapp.MyApp;
import myview.CustomProgressDialog;
import myview.GridViewForScrollView;
import myview.PullLoadMoreRecyclerView;
import util.MyLog;
import util.OrderEventMessage;
import util.RequestManager;

public class ApplicationFragment extends Fragment {

    private View view;
    private Context mcontext;
    private LinearLayout ll_search;
    private LinearLayout ll_content;
    private LinearLayout ll_nodata;
    private String[] caiarr;
    private List<ShaixuanBean> imglist = new ArrayList<>();
    private MyApp myapp;
    private String token;
    private String searchcontent = "";
    private int page = 1;
    private int size = 10;
    private List<ApplicationDataBean.DataBean> temappliList = new ArrayList<>();
    private List<ApplicationDataBean.DataBean> appliList = new ArrayList<>();
    private ApplicationRecyclerViewAdapter adapter;
    private PullLoadMoreRecyclerView goodsRecycleView;
    private int width;
    private int heightPixels;
    private View bottomView;
    private LinearLayout loadLlay;
    private String apptype = "";
    private String textData;
    private SharedPreferences sharedPreferences;
    private CustomProgressDialog customProgressDialog;
    private ContentDataBean.DataBean textContent;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        MyLog.e("Activity:", this.getClass().getName().toString());
        view = inflater.inflate(R.layout.fragment_application, container, false);
        mcontext = getActivity();
        myapp = (MyApp) mcontext.getApplicationContext();
        EventBus.getDefault().register(this);
        sharedPreferences = mcontext.getSharedPreferences("userInfo", Context.MODE_PRIVATE);
        token = sharedPreferences.getString("token", "");
        apptype = sharedPreferences.getString("apptype", "0");
        textData = sharedPreferences.getString("textData", "");

        customProgressDialog = new CustomProgressDialog(mcontext, "", R.style.CommProgressDialog);
        customProgressDialog.show();
        WindowManager.LayoutParams params = customProgressDialog.getWindow().getAttributes();
        params.alpha = 0.7f;//取值为0-1之间  0是全透明，1是不透明
        params.dimAmount=0f;   //取值为0-1之间  1是全黑
//		params.width = 180;//设置进度条的宽度
//		params.height = 180;//设置进度条的宽度
        customProgressDialog.getWindow().setAttributes(params);
        customProgressDialog.show();

        getScreenDen();
        initView();
        initTopView();
        initLin();
        initData();
        getData();

        return view;

    }

    private void initView() {
        ll_search = view.findViewById(R.id.ll_search);
        ll_content = view.findViewById(R.id.ll_content);
        ll_nodata = view.findViewById(R.id.ll_nodata);
        TextView tv_title = view.findViewById(R.id.tv_title);
        TextView tv_nodata = view.findViewById(R.id.tv_nodata);
        goodsRecycleView = view.findViewById(R.id.rclv_goods);
        adapter = new ApplicationRecyclerViewAdapter(temappliList, mcontext, myapp,width,"");
        setHeader(goodsRecycleView);
        goodsRecycleView.setAdapter(adapter);
        goodsRecycleView.setLinearLayout();
        goodsRecycleView.setRefreshing(true);
        textContent = new Gson().fromJson(textData, new TypeToken<ContentDataBean.DataBean>() {}.getType());
        if (textContent != null){
            tv_title.setText(textContent.getApplication_title());
            tv_nodata.setText(textContent.getNodata());
        }

    }
    @Subscribe
    public void onEventMainThread(OrderEventMessage event) {
        String message = event.getMessage();
        MyLog.e("message--new--order", message);
        if ("应用场景".equals(message)) {
            String type = event.getType();
            String[] s = type.split("_");
            int item = Integer.parseInt(s[0]);
            int po = Integer.parseInt(s[1]);
            ArrayList<String> images = (ArrayList<String>) appliList.get(po).getImages();
            Intent intent = new Intent(mcontext, ImageActivity.class);
            intent.putExtra("imgs",images);
            intent.putExtra("position",item+"");
            startActivity(intent);
        }

    }
    /**
     * 设置头部布局
     *
     * @param view
     */
    private void setHeader(PullLoadMoreRecyclerView view) {


        //底部加载更多
        bottomView = LayoutInflater.from(mcontext).inflate(R.layout.main_bottom, view, false);
        adapter.setBottomView(bottomView);
    }
    /**
     * 初始化头部控件
     */
    private void initTopView() {


        //加载更多
        loadLlay = (LinearLayout) bottomView.findViewById(R.id.llay_load);
    }

    private void initLin() {
        ll_search.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(mcontext, SearchActivity.class);
                intent.putExtra("activityType","app");
                intent.putExtra("showroom","");
                startActivity(intent);
            }
        });
        goodsRecycleView.setOnPullLoadMoreListener(new PullLoadMoreRecyclerView.PullLoadMoreListener() {
            @Override
            public void onRefresh() {
                page = 1;
                getData();
//                goodsRecycleView.setPullLoadMoreCompleted();
            }

            @Override
            public void onLoadMore() {
                if (temappliList.size() != 0) {

                    customProgressDialog.show();
                    page++;
                    getData();
                }else{
                goodsRecycleView.setPullLoadMoreCompleted();

                }
            }

            @Override
            public void onScrollChanged(int heightTotal) {

            }

            @Override
            public void onScrollState(int type) {

            }
        });
        //店铺列表点击事件
        adapter.setOnItemClickListener(new ApplicationRecyclerViewAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(int position) {
                MyLog.e("条目点击事件",position+"    item");
                ArrayList<String> images = (ArrayList<String>) appliList.get(position).getImages();
                String product = appliList.get(position).getContent();
                Intent intent = new Intent(mcontext, ApplicationActivity.class);
                intent.putExtra("imglist",images);
                intent.putExtra("titlename",product);
                startActivity(intent);
            }
        });
    }

    private void initData() {
        caiarr = new String[]{"乌金木", "雨木双拼桌面板", "黑胡桃栗木混拼桌面"};
        for (int i = 0; i < 3; i++) {
            ShaixuanBean bean = new ShaixuanBean();
            bean.setName(caiarr[i]);
            imglist.add(bean);
        }

    }


    /**
     * 请求数据
     */
    private void getData() {
        temappliList.clear();
        String url = myapp.getWebConfig() + "/api/index/scene";
        HashMap<String, String> paramsMap = new HashMap<>();
        paramsMap.put("token", token);
        paramsMap.put("search", searchcontent);
        paramsMap.put("page", page+"");
        paramsMap.put("size", size+"");
        paramsMap.put("is_material", apptype);
        RequestManager.getInstance(mcontext).requestAsyn(url, RequestManager.TYPE_POST_FORM, paramsMap, new RequestManager.ReqCallBack() {
            @Override
            public void onReqSuccess(Object result) {
                MyLog.e("code--result", result.toString());
                Message msg = new Message();
                try {
                    JSONObject jsonObject = new JSONObject(result.toString());
                    if (jsonObject.getString("code").equals("0")) {

                        msg.obj = jsonObject.getString("msg");
                        msg.arg1 = 0;
                        handler.sendMessage(msg);
                        return;
                    }
                    JSONArray data = jsonObject.getJSONArray("data");
                    temappliList = new Gson().fromJson(data.toString(), new TypeToken<List<ApplicationDataBean.DataBean>>() {
                    }.getType());


                    msg.arg1 = 2;
                    handler.sendMessage(msg);
                } catch (JSONException e) {
                    e.printStackTrace();
                    msg.arg1 = 1;
                    handler.sendMessage(msg);
                }
            }

            @Override
            public void onReqFailed(String errorMsg) {
                MyLog.e("result", errorMsg);
                if (errorMsg.equals("未登录")){
                    Message msg = new Message();
                    msg.arg1 = 11;
                    handler.sendMessage(msg);
                }
            }
        });
    }

    public Handler handler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.arg1) {
                case 0:
                    if (customProgressDialog != null){
                        if (customProgressDialog.isShowing()){
                            customProgressDialog.dismiss();
                        }
                    }
                    String str = (String) msg.obj;
                    Toast.makeText(mcontext, str, Toast.LENGTH_LONG).show();
                    break;
                case 1:
                    if (customProgressDialog != null){
                        if (customProgressDialog.isShowing()){
                            customProgressDialog.dismiss();
                        }
                    }
                    Toast.makeText(mcontext, textContent.getNet_error(), Toast.LENGTH_LONG).show();
                    break;
                case 2:

                    if (customProgressDialog != null){
                        if (customProgressDialog.isShowing()){
                            customProgressDialog.dismiss();
                        }
                    }
                    if (page == 1) {
                        appliList.clear();
                    }
                    appliList.addAll(temappliList);
                    adapter.setDatas(appliList);
                    loadLlay.removeAllViews();
                    goodsRecycleView.setPullLoadMoreCompleted();
                    if (appliList.size() == 0){
                        ll_nodata.setVisibility(View.VISIBLE);
                        goodsRecycleView.setVisibility(View.GONE);
                    }else{
                        ll_nodata.setVisibility(View.GONE);
                        goodsRecycleView.setVisibility(View.VISIBLE);
                    }


                    break;
                case 3:


                    break;
                case 4:

                    break;
                case 11:
                    if (!islogin){
                        islogin = true;
                        sharedPreferences.edit().putString("token", "").commit();
                        Intent intent = new Intent(mcontext, LoginActivity.class);
                        mcontext.startActivity(intent);
                        myapp.destoryActivity("主页面");
                    }
                    break;
            }
        }
    };
    private boolean islogin = false;
    /**
     * 获取屏幕宽度
     */
    private void getScreenDen() {

        WindowManager manager = getActivity().getWindowManager();
        DisplayMetrics dm = new DisplayMetrics();
        manager.getDefaultDisplay().getMetrics(dm);
        //以要素为单位
        width = dm.widthPixels;
        heightPixels = dm.heightPixels;
        MyLog.e("获取屏幕高度", heightPixels + "    高度");
    }
    @Override
    public void onResume() {
        super.onResume();
        MyLog.e("应用","onResume");
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        MyLog.e("应用","onHiddenChanged     "+hidden);
        if (!hidden){
            page = 1;
            getData();
        }
    }
    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

}
